<?php
/**
 * 文件描述  缓存操作类
 * =================================================================
 * 文件名称  Cache.class.php
 * -----------------------------------------------------------------
 * 作    者  YYT<375776626@vip.qq.com>
 * -----------------------------------------------------------------
 * 创建时间  2010-1-20
 * -----------------------------------------------------------------
 * 版权信息  创思工作室
 * =================================================================
 */

class Cache
{
    /* 缓存生命周期 */
    public $lifeTime = 3600;

    public function __input(&$obj, $args)
    {
        $this->obj = $obj;
        $this->inputArgs = $args;
        return $this;
    }

    private function __call($funcName, $funcArgs)
    {
        if ($this->inputArgs['0'] && $this->inputArgs['0'] == -1) {
            return $this->clear($this->obj, $funcName, $funcArgs);
        } else {
            return $this->cacheObj($this->obj, $funcName, $funcArgs, $this->inputArgs['0']);
        }
    }

    private function cacheObj($obj, $funcName, $funcArgs = '', $lifeTime = '')
    {
        /* 缓存名根据类名方法名 */
        $cacheName = get_class($obj) . md5($funcName);
        /* 如果存在参数 */
        $funcArgs && $cacheName .= md5(serialize($funcArgs));

        /* 设置静态属性用于判断是否存在重复调用 */
        static $cache = array();
        if (isset($cache[$cacheName])) {
            return $cache[$cacheName];
        } else {
            if ($cacheFile = access('r',$cacheName)) {
                $cache[$cacheName] = unserialize($cacheFile);
                return $cache[$cacheName];
            } else {
                /* 如果生命周期为空则为默认 */
                !$lifeTime && $lifeTime = $this->lifeTime;
                /* 这里防止为"0"的数据所以再次serialize */
                $runResult = call_user_func_array(array($obj, $funcName), $funcArgs);
                access('w', $cacheName, serialize($runResult), $lifeTime);
                return $runResult;
            }
        }
    }

    private function clear($obj, $funcName, $funcArgs = '')
    {
        $cacheName = get_class($obj) . md5($funcName);
        $funcArgs && $cacheName .= md5(serialize($funcArgs));
        access('c', $cacheName);
    }
}